package com.inter.law;

import com.inter.law.dao.IlCaseDAO;
import com.inter.law.dao.IlCaseDynamicDAO;
import com.inter.law.dao.IlLawerDAO;
import com.inter.law.dao.IlTaskDAO;
import com.inter.law.entity.IlCase;
import com.inter.law.entity.IlCaseDynamic;
import com.inter.law.entity.IlLawer;
import com.inter.law.entity.IlTask;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class LoginAction extends ActionSupport {


    private String username;                    //用户名
    private String password;                    //密码
    private Integer lawer_id;                    //律师_id 表中 主键
    private String index;                        //每次获取案件动态时候下标
    private String index_out;                    //暂时没用
    private int case_id;                        //case_id用于确认某个case中的动态
    private String case_name;
    private List<List<String>> content = new ArrayList<List<String>>();        //多案件动态中的动态内容
    private List<List<String>> content_lawername = new ArrayList<List<String>>();        //多案件动态中的动态内容
    private List<List<String>> content_casename = new ArrayList<List<String>>();        //多案件动态中的动态内容
    private List<List<String>> content_object = new ArrayList<List<String>>();    //多案件动态中的动态参数
    private List<List<String>> content_para = new ArrayList<List<String>>();    //多案件动态中的动态参数
    private List<String> content_case = new ArrayList<String>();                //我的案件iframe中案件名称
    private List<Integer> content_case_para = new ArrayList<Integer>();            //我的案件iframe中案件id
    private List<List<String>> content_time = new ArrayList<List<String>>();    //暂时没什么卵用
    private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    IlCaseDynamicDAO ilCaseDynamicDAO = IlCaseDynamicDAO.getFromApplicationContext(ac);//查找il_case_dynamic表
    IlLawerDAO ilLawerDAO = IlLawerDAO.getFromApplicationContext(ac);
    IlCaseDAO ilCaseDAO = IlCaseDAO.getFromApplicationContext(ac);
    IlTaskDAO ilTaskDAO = IlTaskDAO.getFromApplicationContext(ac);
    private JSONObject jsonObj = new JSONObject();
    private String json;
    Map<String, Object> session = ActionContext.getContext().getSession();

    /**
     * Log in Method
     *
     * @return
     * @throws Exception
     */
    public void addActionError(String anErrorMessage) {                    //一些异常函数，用于调试
        System.out.print("anErrorMessage:" + anErrorMessage + "\n");
    }

    public void addActionMessage(String aMessage) {
        System.out.print("aMessage:" + aMessage + "\n");
    }

    public void addFieldError(String fieldName, String errorMessage) {
        System.out.print("fieldName:" + fieldName + "   errorMessage:" + errorMessage + "\n");
    }

    public static String getWeekOfDate(String strTime) {            //根据日期判断星期几
        String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);                            //
        if (strTime.equals(str))
            str = "今天" + strTime;
        else str = strTime;
        try {
            date = format.parse(strTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return str + weekOfDays[w];
    }

    public String login() throws Exception {            //登录函数
        IlLawerDAO ilLawerDAO = IlLawerDAO.getFromApplicationContext(ac);
        ArrayList list = (ArrayList) ilLawerDAO.findByLawerUsername(username); //根据用户名查找数据库
        System.out.print(1);
        if (list != null && !list.isEmpty()) {
            lawer_id = ((IlLawer) (list.get(0))).getLawerId();                        //后去lawer_id仅仅用于调试
            System.out.println("the user id is : " + lawer_id);
            System.out.println(password);
            System.out.println(((IlLawer) list.get(0)).getLawerPassword().trim());
            if (password.equals(((IlLawer) list.get(0)).getLawerPassword().trim())) {
                System.out.println("登录成功");
                jsonObj.put("code", "true");
            } else {
                System.out.println("密码错误！");
                jsonObj.put("code", "false");
            }
        } else {
            jsonObj.put("code", "noaccount");
            System.out.println("账户不存在");
            //setUsername(username);
        }
        session.put("username", username);                        //将用户名放入session中，方便下几个函数提取
        Integer myId = ((IlLawer) list.get(0)).getLawerId();
        session.put("id", myId);
        json = jsonObj.toString();
        System.out.println(json);
        return SUCCESS;
    }

    /**
     * 加载主页面动态内容
     * @return
     * @throws Exception
     */
    public String jump() throws Exception {                    //登录成功后跳转到contian页面 ，调用的函数


        //System.out.print(username);
        String username = (String) session.get("username");                        //获取username
        System.out.print("username:" + username + "\n");                            //用于调试
        ArrayList list = (ArrayList) ilLawerDAO.findByLawerUsername(username);    //根据用户名查找
        int lawer_id = ((IlLawer) list.get(0)).getLawerId();                        //获取lawer_id
        String lawername = ((IlLawer) list.get(0)).getLawerName();
        list = (ArrayList) ilCaseDynamicDAO.findByLawerId(lawer_id);                //在il_case_dynamic表中根据lawer_id查找案件动态，找到该律师所有的案件动态
        String strTime = new String();                                            //获取strTime用于每次得到案件动态时比较
        String strTime_test = new String();                                        //获得案件动态时间
        int num = 0;                                                             //num=index 0,5,10

        if (index == null || index == "") {                                            //index初始值为0，第一次加载进入页面，没有点击更多动态时
            index = new String("0");
        }

        int last_time = Integer.parseInt(index);                                //获取上一次时的下标
        //System.out.print("last_time:"+last_time+"\n");
        index = String.valueOf(last_time + 5);                                    //这两行代码并没有什么卵用
        jsonObj.put("code", index);
        num = last_time;                                                        //从上一次下标处开始取值

        //System.out.print("last_time"+last_time+"\n");
        //System.out.print("num"+num+"\n");
        if (list != null && !list.isEmpty()) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");                //定义格式，不显示毫秒
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm");                    //定义格式，显示小时，分钟
            //Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
            if (num < list.size())
                strTime = df.format(((IlCaseDynamic) list.get(list.size() - 1 - num)).getContentTime()); // yyyy-mm-dd 反序本次第一条记录
            String str, str2;
            content.clear();                                                        //清空list
            content_para.clear();
            if (num == list.size()) return SUCCESS;                                    //防止出现两次没有多余动态
            for (int i = 0; num < 5 + last_time && num < list.size(); i++) {                    //反序获得从上一次结束下标处开始的5个案件动态
                //	System.out.print(i+"\n");
                ArrayList<String> lists_content = new ArrayList<String>();            //list
                ArrayList<String> lists_time = new ArrayList<String>();            //list
                ArrayList<String> lists_para = new ArrayList<String>();
                ArrayList<String> lists_dynamicname = new ArrayList<String>();
                ArrayList<String> lists_casename = new ArrayList<String>();
                ArrayList<String> lists_object = new ArrayList<String>();
                //		content.add(i,new ArrayList<String>());
                //		content_para.add(i,new ArrayList<String>());

                if (i == 0 && num != 0)                                                        //点击更多动态时进入此if
                {
                    strTime_test = df.format(((IlCaseDynamic) list.get(list.size() - num)).getContentTime()); // yyyy-mm-dd 取得上次最后一条记录
                    //System.out.print("strTime_test: "+strTime_test+" strTime:"+strTime+"\n");
                    if (strTime_test.equals(strTime))                         //日期相同，则不加日期
                    {
                        lists_content.add(0, "  ");
                        //lists_para.add(0,"1");
                    } else {
                        lists_content.add(0, getWeekOfDate(strTime));        //不然加日期
                        //lists_para.add(0,"1");
                    }
                } else {                                                                //没有点击更多动态时也要加入日期，初始页面
                    lists_content.add(0, getWeekOfDate(strTime));
                    //lists_para.add(0,"1");
                }
                lists_para.add(0, " ");
                lists_time.add(0, " ");
                lists_dynamicname.add(0, " ");
                lists_casename.add(0, " ");
                lists_object.add(0, " ");
                //	content.get(i).add(0,getWeekOfDate(strTime)); //每个二层list第一个元素都为日期

                //	content_para.get(i).add(0,"1");  //此处不添加数据，仅为保持下标一致

                for (int j = 1; num < 5 + last_time && num < list.size(); j++, num++) {                //查找一个日期中的所有案件动态
                    //	System.out.print("num:"+num+"\n");
                    str = df.format(((IlCaseDynamic) list.get(list.size() - num - 1)).getContentTime()); //yyyy-hh-mm 从数据库中得到时间
                    str2 = df2.format(((IlCaseDynamic) list.get(list.size() - num - 1)).getContentTime());//定义格式，显示小时，分钟
                    //System.out.print(str);
                    if (!str.equals(strTime)) {                        //与局部变量相比较，如果相同，则继续插入，不同则进入下一个list
                        strTime = str;
                        //System.out.print(strTime);
                        break;

                    }
                    int type = ((IlCaseDynamic) list.get(list.size() - num - 1)).getTypeId();
                    System.out.print("type:" + type + "\n");
                    int case_id = ((IlCaseDynamic) list.get(list.size() - num - 1)).getCaseId();    //获取case_id
                    IlCase ilcase = ilCaseDAO.findById(case_id);                                //获取il_case，再得到案件名
                    int task_id;
                    IlTask task = new IlTask();
                    IlLawer lawer = new IlLawer();
                    lists_time.add(j, str2);
                    lists_dynamicname.add(j, lawername);    //生成动态的律师姓名
                    lists_casename.add(j, ilcase.getCaseName());                                                //动态的案件名
                    switch (type) {

                        case 12:                                                                    //更新任务截止日期
                            task_id = Integer.valueOf(((IlCaseDynamic) list.get(list.size() - num - 1)).getContent());
                            //System.out.print("task_id:"+task_id+"\n");

                            task = ilTaskDAO.findById(task_id);
                            //System.out.print("get task"+"\n");

                            lists_para.add(j, task.getContent());                                //任务名
                            //System.out.print("task.getContent():"+task.getContent()+"\n");
                            SimpleDateFormat df3 = new SimpleDateFormat("MM-dd");                //定义格式，只显示月份 日期
                            lists_object.add(j, df3.format(task.getTaskDateline()));                //只显示月份 日期
                            //System.out.print(df3.format(task.getTaskDateline())+"\n");
                            lists_content.add(j, Integer.toString(type));                        //type 动态类型

                            break;
                        case 11:                                                                    //创建，完成，重新开始任务
                        case 13:
                        case 14:
                            task_id = Integer.valueOf(((IlCaseDynamic) list.get(list.size() - num - 1)).getContent());
                            System.out.print("task_id:" + task_id + "\n");

                            task = ilTaskDAO.findById(task_id);
                            System.out.print("get task" + "\n");

                            lists_para.add(j, task.getContent());                                //任务名
                            lawer = ilLawerDAO.findById(task.getLawerId());
                            System.out.print("task.getLawerId():" + task.getLawerId() + "\n");

                            lists_object.add(j, lawer.getLawerName());                            //执行该任务的律师名
                            System.out.print("lawer.getLawerName():" + lawer.getLawerName() + "\n");
                            lists_content.add(j, Integer.toString(type));

                            break;
                        case 21:                                                                    //上传文件
                            lists_object.add(j, " ");
                            lists_para.add(j, ((IlCaseDynamic) list.get(list.size() - num - 1)).getContent());//上传的文件名
                            lists_content.add(j, "21");
                            break;
                        case 31:                                                                    //创建案件

                            lists_object.add(j, " ");
                            lists_para.add(j, " ");
                            lists_content.add(j, "31");
                            break;
                    }
                    //((IlCaseDynamic) list.get(i)).getContentTime().toString();
                    //content.get(i).add(j,((IlCaseDynamic) list.get(list.size()-num-1)).getLawerName()+((IlCaseDynamic) list.get(list.size()-num-1)).getContent());
                    //content_para.get(i).add(j,((IlCaseDynamic) list.get(list.size()-num-1)).getContentPara());
                    //System.out.print(lists_content.get(j));
                    //System.out.print(((IlCaseDynamic) list.get(list.size()-num-1)).getContentPara()+"\n");
                }
                content_time.add(i, lists_time);
                content.add(i, lists_content);
                content_para.add(i, lists_para);
                content_lawername.add(i, lists_dynamicname);
                content_casename.add(i, lists_casename);
                content_object.add(i, lists_object);
            }
        } else {                                                        //输出列表为空，用于调试
            System.out.print("list is empty");
        }
        if (num == list.size()) {                                        //没有更多动态添加时
            ArrayList<String> lists_content = new ArrayList<String>();
            ArrayList<String> lists_para = new ArrayList<String>();
            lists_content.add("没有多余动态");
            lists_para.add("  ");
            content.add(lists_content);
            content_para.add(lists_para);
        }
        jsonObj.put("code", "true");                                    //没有什么卵用
        json = jsonObj.toString();
        //System.out.print("jump");
        return SUCCESS;
    }

    public String overjump() throws Exception {
        return SUCCESS;
    }

    public String jumptocase() throws Exception {
        String username = (String) session.get("username");
        //	System.out.print("username:"+username+"\n");
        ArrayList list = (ArrayList) ilLawerDAO.findByLawerUsername(username);
        if (list != null && !list.isEmpty()) {
            lawer_id = ((IlLawer) (list.get(0))).getLawerId();

            list = (ArrayList) ilCaseDAO.findByCaseLawerId(lawer_id);           //获得相关的案件
            System.out.append("lawer_id: " + lawer_id);
            System.out.print("list.size: " + list.size());
            for (int i = 1; i <= list.size(); i++) {
                content_case.add((String) ((IlCase) (list.get(list.size() - i))).getCaseName());                //案件名称
                content_case_para.add((Integer) ((IlCase) (list.get(list.size() - i))).getCaseId());                //案件id
            }

        }
        return SUCCESS;
    }

    public String jumptosinglecase() throws Exception {                            //跳转到单个案例页面具体请参考上一个函数大体相同。

        //System.out.print(username);
        String username = (String) session.get("username");
        System.out.print("username:" + username + "\n");
        ArrayList list = (ArrayList) ilLawerDAO.findByLawerUsername(username);        //username->id
        int lawer_id = ((IlLawer) list.get(0)).getLawerId();
        String lawername = ((IlLawer) list.get(0)).getLawerName();
        list = (ArrayList) ilCaseDynamicDAO.findByLawerAndCase(lawer_id, case_id);        //根据lawer id和case_id查找
        System.out.print("lawer_id:" + lawer_id + "case_id:" + case_id + "\n");
        System.out.print("list_size:" + list.size() + "\n");
        String strTime = new String();
        String strTime_test = new String();
        int num = 0;    //num=index 0,5,10
        IlCase ilcase = ilCaseDAO.findById(case_id);
        case_name = ilcase.getCaseName();

        if (index == null || index == "") {
            index = new String("0");
        }

        int last_time = Integer.parseInt(index);
        index = String.valueOf(last_time + 10);
        jsonObj.put("code", index);
        num = last_time;

        //System.out.print("last_time"+last_time+"\n");
        //System.out.print("num"+num+"\n");
        if (list != null && !list.isEmpty()) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//定义格式，不显示毫秒
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm");//定义格式，显示小时，分钟
            //Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
            if (num < list.size())
                strTime = df.format(((IlCaseDynamic) list.get(list.size() - 1 - num)).getContentTime()); // yyyy-mm-dd 反序本次第一条记录
            String str, str2;
            content.clear();
            content_para.clear();
            if (num == list.size()) return SUCCESS;                                    //防止出现两次没有多余动态
            for (int i = 0; num < 10 + last_time && num < list.size(); i++) {     //每次插入10个动态，单个案件页面
                //	System.out.print(i+"\n");
                ArrayList<String> lists_content = new ArrayList<String>();
                ArrayList<String> lists_para = new ArrayList<String>();
                //		content.add(i,new ArrayList<String>());
                //		content_para.add(i,new ArrayList<String>());

                if (i == 0 && num != 0) {
                    strTime_test = df.format(((IlCaseDynamic) list.get(list.size() - num)).getContentTime()); // yyyy-mm-dd 取得上次最后一条记录
                    //System.out.print("strTime_test: "+strTime_test+" strTime:"+strTime+"\n");
                    if (strTime_test.equals(strTime))                         //日期相同，则不加日期
                    {
                        lists_content.add(0, "  ");
                        lists_para.add(0, "1");
                    } else {
                        lists_content.add(0, getWeekOfDate(strTime));        //不然加日期
                        lists_para.add(0, "1");
                    }
                } else {
                    lists_content.add(0, getWeekOfDate(strTime));
                    lists_para.add(0, "1");
                }
                //	content.get(i).add(0,getWeekOfDate(strTime)); //每个二层list第一个元素都为日期

                //	content_para.get(i).add(0,"1");  //此处不添加数据，仅为保持下标一致

                for (int j = 1; num < 10 + last_time && num < list.size(); j++, num++) {  //每次插入10个动态，单个案件页面
                    //	System.out.print("num:"+num+"\n");
                    str = df.format(((IlCaseDynamic) list.get(list.size() - num - 1)).getContentTime()); //yyyy-hh-mm 从数据库中得到时间
                    str2 = df2.format(((IlCaseDynamic) list.get(list.size() - num - 1)).getContentTime());//定义格式，显示小时，分钟
                    //System.out.print(str);
                    if (!str.equals(strTime)) {    //与局部变量相比较，如果相同，则继续插入，不同则进入下一个list
                        strTime = str;
                        //System.out.print(strTime);
                        break;

                    }
                    //((IlCaseDynamic) list.get(i)).getContentTime().toString();


                    lists_content.add(j, str2 + "     " + lawername + "在案件" + case_name +
                            "中" + ((IlCaseDynamic) list.get(list.size() - num - 1)).getContent());
                    lists_para.add(j, ((IlCaseDynamic) list.get(list.size() - num - 1)).getContentPara());
                    //content.get(i).add(j,((IlCaseDynamic) list.get(list.size()-num-1)).getLawerName()+((IlCaseDynamic) list.get(list.size()-num-1)).getContent());
                    //content_para.get(i).add(j,((IlCaseDynamic) list.get(list.size()-num-1)).getContentPara());
                    //System.out.print(lists_content.get(j));
                    //System.out.print(((IlCaseDynamic) list.get(list.size()-num-1)).getContentPara()+"\n");
                }
                content.add(i, lists_content);
                content_para.add(i, lists_para);
            }
        } else {
            System.out.print("list is empty");
        }
        if (num == list.size()) {
            ArrayList<String> lists_content = new ArrayList<String>();
            ArrayList<String> lists_para = new ArrayList<String>();
            lists_content.add("没有多余动态");
            lists_para.add("  ");
            content.add(lists_content);
            content_para.add(lists_para);
        }
        return SUCCESS;
    }

    public IlLawer login(IlLawer lawer) throws Exception {
        String hql = "from il_lawer u where u.lawer_username'";

        return lawer;

    }

    /**
     * Register Method
     *
     * @return
     */
    public String regist() {
        System.out.println("regist method");
        return SUCCESS;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void validate() {
        if ((null == username) ||
                "".equals(username)) {
            addFieldError("username", getText("user.required"));
        }

        if ((null == password) ||
                "".equals(password)) {
            addFieldError("password", getText("pass.required"));
        }
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

    public JSONObject getJsonObj() {
        return jsonObj;
    }

    public void setJsonObj(JSONObject jsonObj) {
        this.jsonObj = jsonObj;
    }

    public List<List<String>> getContent() {
        //System.out.print("getContent"+"\n"+content.get(0).get(0));
        return content;
    }

    public void setContent(List<List<String>> content) {
        this.content = content;
        //System.out.print("setContent"+"\n");
    }

    public List<List<String>> getContent_para() {
        //System.out.print("getContent_para"+"\n");
        return content_para;
    }

    public void setContent_para(List<List<String>> content_para) {
        //System.out.print("setContent_para"+"\n");
        this.content_para = content_para;
    }

    public List<List<String>> getContent_time() {
        return content_time;
    }

    public void setContent_time(List<List<String>> content_time) {
        this.content_time = content_time;
    }

    public String getIndex() {
        //System.out.print("getIndex"+"\n");
        return index;
    }

    public void setIndex(String index) {
        //System.out.print("setIndex"+"\n");
        this.index = index;
    }

    public String getIndex_out() {
        return index_out;
    }

    public void setIndex_out(String index_out) {
        this.index_out = index_out;
    }

    public List<String> getContent_case() {
        return content_case;
    }

    public void setContent_case(List<String> content_case) {
        this.content_case = content_case;
    }

    public List<Integer> getContent_case_para() {
        return content_case_para;
    }

    public void setContent_case_para(List<Integer> content_case_para) {
        this.content_case_para = content_case_para;
    }

    public int getCase_id() {
        return case_id;
    }

    public void setCase_id(int case_id) {
        this.case_id = case_id;
    }

    public String getCase_name() {
        return case_name;
    }

    public void setCase_name(String case_name) {
        this.case_name = case_name;
    }

    public List<List<String>> getContent_lawername() {
        return content_lawername;
    }

    public void setContent_lawername(List<List<String>> content_lawername) {
        this.content_lawername = content_lawername;
    }

    public List<List<String>> getContent_casename() {
        return content_casename;
    }

    public void setContent_casename(List<List<String>> content_casename) {
        this.content_casename = content_casename;
    }

    public List<List<String>> getContent_object() {
        return content_object;
    }

    public void setContent_object(List<List<String>> content_object) {
        this.content_object = content_object;
    }
}
